/**
 * @author Jason Pratt, David Culyba
 */

package edu.cmu.cs.stage3.alice.authoringtool.dialog;

import edu.cmu.cs.stage3.resourceBundle.I18n;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool;
import edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources;
import edu.cmu.cs.stage3.swing.ContentPane;

public abstract class AliceAlertContentPane extends ContentPane {

 public final static int LESS_DETAIL_MODE = 0;
 public final static int MORE_DETAIL_MODE = 1;

 protected int mode = -1;
 protected edu.cmu.cs.stage3.alice.authoringtool.util.ImagePanel errorIconPanel = new edu.cmu.cs.stage3.alice.authoringtool.util.ImagePanel();
 protected edu.cmu.cs.stage3.alice.authoringtool.util.StyledStreamTextPane detailTextPane = new edu.cmu.cs.stage3.alice.authoringtool.util.StyledStreamTextPane();
 protected edu.cmu.cs.stage3.alice.authoringtool.util.StyleStream detailStream;


 public AliceAlertContentPane () {
  init();
  }

 //Rem @Override
 public void preDialogShow (javax.swing.JDialog dialog) {
  super.preDialogShow( dialog );
  }

 //Rem @Override
 public void postDialogShow (javax.swing.JDialog dialog) {
  super.postDialogShow( dialog );
 } 

 //Rem @Override
 public String getTitle () {
  return I18n.getString("msgAlertSubmitTitle"); // "iVProg - Alert"
  }

 //Rem @Override
 public void addOKActionListener (java.awt.event.ActionListener l) {
  cancelButton.addActionListener(l);
  }

 protected void init () {
  jbInit();
  setMode( LESS_DETAIL_MODE );
  }

 public void setSubmitBugButtonEnabled (boolean b) {
  if (b != buttonPanel.isAncestorOf( submitBugButton ) ) {
   if (b) {
    buttonPanel.add( submitBugButton, new java.awt.GridBagConstraints( 1, 0, 1, 1, 0.0, 0.0, java.awt.GridBagConstraints.WEST, java.awt.GridBagConstraints.NONE, new java.awt.Insets( 8, 0, 8, 0 ), 0, 0 ) );
   } else {
    buttonPanel.remove( submitBugButton );
    }
   }
  }

 public void setMessage (String message) {
  messageLabel.setText( message );
  }


 //Rem @Override
 public java.awt.Dimension getPreferredSize () {
  java.awt.Dimension preferredSize = super.getPreferredSize();
  return preferredSize;
  }

 protected void setLessDetail () {
  detailButton.setText(I18n.getString("msgAlertSubmitMore") + " >>"); // "More Detail"
  this.remove(detailScrollPane);
  this.add(detailPanel, BorderLayout.CENTER);

  buttonPanel.removeAll();
  buttonConstraints.gridx = 0;
  buttonPanel.add(submitBugButton, buttonConstraints);
  buttonConstraints.gridx++;
  buttonPanel.add(cancelButton, buttonConstraints );
  buttonConstraints.gridx++;
  glueConstraints.gridx = buttonConstraints.gridx;
  buttonPanel.add(buttonGlue, glueConstraints);
  buttonConstraints.gridx++;
  buttonPanel.add(detailButton, buttonConstraints);
  }

 protected void setMoreDetail () {
  detailButton.setText(I18n.getString("msgAlertSubmitLess")+" <<"); // "Less Detail"
  this.remove(detailPanel);
  this.add(detailScrollPane, BorderLayout.CENTER);

  buttonPanel.removeAll();
  buttonConstraints.gridx = 0;
  buttonPanel.add(submitBugButton, buttonConstraints);
  buttonConstraints.gridx++;  
  buttonPanel.add(copyButton, buttonConstraints);
  buttonConstraints.gridx++;
  buttonPanel.add(cancelButton, buttonConstraints );
  buttonConstraints.gridx++;
  glueConstraints.gridx = buttonConstraints.gridx;
  buttonPanel.add(buttonGlue, glueConstraints);
  buttonConstraints.gridx++; 
  buttonPanel.add(detailButton, buttonConstraints);
  }

 protected void handleModeSwitch (int mode) {
  if (mode == LESS_DETAIL_MODE ) {
   setLessDetail();
  } else if (mode == MORE_DETAIL_MODE ) {
   setMoreDetail();
  } else {
   throw new IllegalArgumentException(I18n.getString("msgAlertSubmitIllegal") + ": " + mode ); // "Illegal mode" 
   }
  }

 public void setMode (int mode) {
  if (this.mode != mode ) {
   this.mode = mode;
   handleModeSwitch(mode);
   packDialog();
   }
  }


 public void toggleMode () {
  if (mode == LESS_DETAIL_MODE ) {
   setMode( MORE_DETAIL_MODE );
  } else {
   setMode( LESS_DETAIL_MODE );
   }
  }

 protected void writeAliceHeaderToTextPane () {
  detailTextPane.setText( "" );
  detailStream.println( messageLabel.getText() + "\n" );
  detailStream.println();

  detailStream.println("");
  String[] systemProperties = { "os.name", "os.version", "os.arch", "java.vm.name", "java.vm.version", "user.dir" };
  //LOB for (String systemPropertie : systemProperties)
  int t_tam = systemProperties!=null ? systemProperties.length : 0;
  for (int i_i=0; i_i<t_tam; i_i++) {
   detailStream.println( systemProperties[i_i] + ": " + System.getProperty( systemProperties[i_i] ) ); //L systemPropertie + ": " + System.getProperty( systemPropertie )
   }
  detailStream.println();
  }

 // From 'this.submitBugButton_actionPerformed(ActionEvent e)'
 protected void submitBug () {
  String stacktraceID = postStacktrace();
  AuthoringTool authoringTool = AuthoringTool.getInstance(); // to update message after submition try
  // String urlString = edu.cmu.cs.stage3.util.StrUtilities.submitError; // "http://alice.org/bugreport/submit.php"
  // System.out.println("AliceAlertContentPane.java: submitBug(): urlString="+urlString+" stacktraceID="+stacktraceID);
  int resp = -1;
  try {
   //L AuthoringToolResources.openURL( urlString + "&pasteStacktrace=" + stacktraceID );
   resp = edu.cmu.cs.stage3.util.StrUtilities.submitPOST(stacktraceID);
  } catch( Throwable t ) {
   authoringTool.showErrorDialog( I18n.getString("msgAlertSubmitFail"), t ); //L Unable to open bug report web page.
   }
  try { // Update messege of 'StoreElementProgressPane worldStoreProgressPane' in 'edu/cmu/cs/stage3/alice/authoringtool/AuthoringTool'
   String msg = "";
   if (resp==1) // submited successfully
      msg = "msgAlertSubmitSuccess"; // The bug report were successfully submitted. Thanks for the information! 
   else
   if (resp==-1) // wasn't possible to submit bug report
      msg = "msgAlertSubmitFail"; // Unable to open bug report web page.
   else
   if (resp==-2) // wasn't possible to certify the submition of the bug report
      msg = "msgAlertSubmitNotCertified"; // The bug report were submitted, but I couldn't get any confirmation from ther iVprog Web page.
   // StoreElementProgressPane worldStoreProgressPane = authoringTool.getWorldStoreProgressPane(); // worldStoreProgressPane;
   String msg0 = messageLabel.getText(); // protected JTextArea messageLabel = new JTextArea();
   messageLabel.setText(msg0 + I18n.getString(msg)); // protected JTextArea messageLabel = new JTextArea();

  } catch (Exception e ) {
   // src/
   //  void dialogInit (): 'worldStoreProgressPane = new StoreElementProgressPane(...)'
   }
  } // void submitBug()

 //Rem @SuppressWarnings("deprecation")
 protected String postStacktrace () {
  try {
   //L java.net.URL url = new java.net.URL(edu.cmu.cs.stage3.util.StrUtilities.submitErrorTrace); // "http://www.alice.org/bugreport/stacktrace.php"
   //L java.net.URLConnection connection = url.openConnection();
   //L connection.setDoInput( true );
   //L connection.setDoOutput( true );
   //L connection.setUseCaches( false );
   //L connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );

   String stacktrace = java.net.URLEncoder.encode(detailTextPane.getText());
   while (stacktrace.indexOf( "%0D" ) > -1 ) { // delete the carriage returns
    int i = stacktrace.indexOf( "%0D" );
    stacktrace = stacktrace.substring( 0, i ) + stacktrace.substring( i + 3 );
    }
   //L String content = "stacktrace=" + stacktrace;
   String content = stacktrace;
   //L java.io.DataOutputStream output = new java.io.DataOutputStream( new java.io.BufferedOutputStream( connection.getOutputStream() ) );
   //L output.writeBytes( content );
   //L output.flush();
   //L output.close();

   //L // must open input stream after output stream is closed in order for the data to be posted
   //L java.io.BufferedReader input = new java.io.BufferedReader( new java.io.InputStreamReader( connection.getInputStream() ) );
   //L String stacktraceIDString = input.readLine();
   //L input.close();
   //L return stacktraceIDString;
   return content;
  } catch( Throwable t ) {
   AuthoringTool.getInstance().showErrorDialog(I18n.getString("msgAlertSubmitErrorPost"), t ); //  "Error posting stacktrace to bug database."
   return "0";
   }
  }

 protected void copyDetailText () {
  String detailText = detailTextPane.getText();
  java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents( new java.awt.datatransfer.StringSelection( detailText ), AuthoringTool.getInstance() );
  }


 ///////////////
 // Callbacks
 ///////////////
 void detailButton_actionPerformed (ActionEvent e) {
  toggleMode();
  }

 void submitBugButton_actionPerformed (ActionEvent e) {
  submitBug();
  }

 void copyButton_actionPerformed (ActionEvent e) {
  copyDetailText();
  }

 /////////////////////
 // Autogenerated
 /////////////////////

 protected JPanel buttonPanel = new JPanel();
 protected JPanel messagePanel = new JPanel();
 protected JPanel detailPanel = new JPanel();
 protected JScrollPane detailScrollPane = new JScrollPane();
 protected JTextArea messageLabel = new JTextArea();
 protected JButton submitBugButton = new JButton();
 protected JButton copyButton = new JButton();
 protected JButton cancelButton = new JButton();
 protected JButton detailButton = new JButton();

 protected GridBagConstraints buttonConstraints = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0);
 protected GridBagConstraints glueConstraints = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0);
 protected Component buttonGlue;

 // src/edu/cmu/cs/stage3/alice/authoringtool/AuthoringTool.java
 // src/edu/cmu/cs/stage3/alice/authoringtool/dialog/ErrorContentPane.java
 private void jbInit () {
  this.setLayout(new BorderLayout());
  this.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));


  buttonGlue = Box.createHorizontalGlue();

  messageLabel.setEditable(false);
  messageLabel.setLineWrap(true);
  messageLabel.setOpaque(false);
  messageLabel.setPreferredSize(new java.awt.Dimension(402, 1));
  messageLabel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
  messageLabel.setText(I18n.getString("msgAlertSubmitErrorUnknown")); // "An unknown error has occurred."

  cancelButton.setText(I18n.getString("msgCancel")); 

  detailButton.setText(I18n.getString("msgAlertSubmitMore") + " >>"); // More Detail
  detailButton.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed (ActionEvent e) {
    detailButton_actionPerformed(e);
    }
   });
  submitBugButton.setText(I18n.getString("msgAlertSubmitBug")); // "Submit Bug"
  submitBugButton.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(ActionEvent e) {
    submitBugButton_actionPerformed(e); // submit bug report
    }
  });
  copyButton.setText(I18n.getString("msgAlertSubmitCopy")); // "Copy Error to Clipboard"
  copyButton.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed (ActionEvent e) {
    copyButton_actionPerformed(e);
    }
   });

  messagePanel.setLayout(new BorderLayout());
  messagePanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
  detailPanel.setLayout(new BorderLayout());
  detailPanel.setBorder(null);
  detailPanel.setPreferredSize(new java.awt.Dimension(492, 0));
  buttonPanel.setBorder(BorderFactory.createEmptyBorder(6,0,0,0));
  buttonPanel.setLayout(new GridBagLayout());

  java.net.URL errorImageResources = edu.cmu.cs.stage3.alice.authoringtool.JAlice.class.getResource( "images/errorDialogueIcon.png" );
  errorIconPanel.setImage( java.awt.Toolkit.getDefaultToolkit().createImage( errorImageResources ) );
  messagePanel.add( errorIconPanel, java.awt.BorderLayout.WEST );
  messagePanel.add(messageLabel, BorderLayout.CENTER);

  detailTextPane.setEditable( false );
  detailStream = detailTextPane.getNewStyleStream( detailTextPane.stdErrStyle );
  detailScrollPane.setViewportView( detailTextPane );
  detailScrollPane.setPreferredSize(new java.awt.Dimension(490, 400));

  add( messagePanel, BorderLayout.NORTH );
  add(detailPanel, BorderLayout.CENTER);
  add( buttonPanel, BorderLayout.SOUTH );
  }

 }

